const { DataTypes } = require('sequelize');
const sequelize = require('../config/database');
const User = require('./User');
const Video = require('./Video');

// 点赞模型定义
const Like = sequelize.define('Like', {
  // 主键ID
  id: {
    type: DataTypes.BIGINT,
    primaryKey: true,
    autoIncrement: true,
    allowNull: false
  },
  
  // 用户ID
  user_id: {
    type: DataTypes.BIGINT,
    allowNull: false,
    references: {
      model: 'users',
      key: 'id'
    },
    onDelete: 'CASCADE'
  },
  
  // 视频ID
  video_id: {
    type: DataTypes.BIGINT,
    allowNull: false,
    references: {
      model: 'videos',
      key: 'id'
    },
    onDelete: 'CASCADE'
  },
  
  // 创建时间
  createdAt: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW
  },
  
  // 更新时间
  updatedAt: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW
  }
}, {
  // 表配置
  tableName: 'likes',
  timestamps: true,
  underscored: true, // 使用下划线命名
  charset: 'utf8mb4',
  collate: 'utf8mb4_unicode_ci',
  indexes: [
    {
      unique: true,
      fields: ['user_id', 'video_id']
    },
    {
      fields: ['user_id']
    },
    {
      fields: ['video_id']
    }
  ]
});

// 关联关系
Like.belongsTo(User, { foreignKey: 'user_id', as: 'user' });
Like.belongsTo(Video, { foreignKey: 'video_id', as: 'video' });

// 创建点赞前的钩子：检查是否已经点赞
Like.beforeCreate(async (like, options) => {
  const existingLike = await Like.findOne({
    where: {
      user_id: like.user_id,
      video_id: like.video_id
    }
  });
  
  if (existingLike) {
    throw new Error('用户已经点赞过该视频');
  }
});

// 创建点赞后的钩子：更新视频点赞数
Like.afterCreate(async (like) => {
  const video = await Video.findByPk(like.video_id);
  if (video) {
    await video.incrementLikeCount();
  }
});

// 删除点赞后的钩子：更新视频点赞数
Like.afterDestroy(async (like) => {
  const video = await Video.findByPk(like.video_id);
  if (video) {
    await video.decrementLikeCount();
  }
});

// 类方法：检查用户是否点赞了视频 (兼容旧方法名)
Like.isUserLikedVideo = async function(userId, videoId) {
  const like = await this.findOne({
    where: {
      user_id: userId,
      video_id: videoId
    }
  });
  return like !== null;
};

// 类方法：检查用户是否点赞了视频 (控制器使用的方法名)
Like.isLiked = async function(userId, videoId) {
  return await this.isUserLikedVideo(userId, videoId);
};

// 类方法：点赞视频
Like.likeVideo = async function(userId, videoId) {
  try {
    const like = await this.create({
      user_id: userId,
      video_id: videoId
    });
    return { liked: true, like };
  } catch (error) {
    return { liked: false, error: error.message };
  }
};

// 类方法：取消点赞
Like.unlikeVideo = async function(userId, videoId) {
  const deleted = await this.destroy({
    where: {
      user_id: userId,
      video_id: videoId
    }
  });
  return { unliked: deleted > 0 };
};

// 类方法：切换点赞状态 (控制器使用的方法)
Like.toggleLike = async function(userId, videoId) {
  // 检查是否已经点赞
  const isLiked = await this.isUserLikedVideo(userId, videoId);
  
  if (isLiked) {
    // 取消点赞
    await this.unlikeVideo(userId, videoId);
    // 获取更新后的点赞数
    const video = await Video.findByPk(videoId);
    return { liked: false, likeCount: video ? video.like_count : 0 };
  } else {
    // 点赞
    await this.likeVideo(userId, videoId);
    // 获取更新后的点赞数
    const video = await Video.findByPk(videoId);
    return { liked: true, likeCount: video ? video.like_count : 0 };
  }
};

// 为了简化，暂时移除自定义的findAndCountAll方法，让Sequelize自动处理
// 如果需要自定义实现，可以在控制器中进行处理

// 类方法：获取用户点赞的视频列表
Like.getUserLikedVideos = async function(userId, limit = 20, offset = 0) {
  return await Video.findAll({
    include: [
      {
        model: Like,
        as: 'likes',
        where: {
          user_id: userId
        }
      },
      {
        model: User,
        as: 'user',
        attributes: ['id', 'username', 'avatar']
      }
    ],
    where: {
      status: 1 // 只返回审核通过的视频
    },
    order: [['likes', 'created_at', 'DESC']],
    limit,
    offset
  });
};

// 类方法：获取视频的点赞用户列表
Like.getVideoLikes = async function(videoId, limit = 20, offset = 0) {
  return await User.findAll({
    include: [
      {
        model: Like,
        as: 'likes',
        where: {
          video_id: videoId
        }
      }
    ],
    order: [['likes', 'created_at', 'DESC']],
    limit,
    offset
  });
};

module.exports = Like;

// 导出到全局，方便其他模块使用
global.Like = Like;